require 'rexml/document'
require 'wpspider/common/db_connector'
require 'wpspider/common/wppage'

module WPSpider
  module WebService

    #
    # Search Command class.
    #
    class SearchCommand
      # Page name.
      attr_accessor :name
      #
      attr_accessor :type

      #
      # Constructor.
      #
      def initialize()
        @name = nil
      end

      #
      # Executes search command.
      #
      def execute()
        page = nil
        if(@name)
          db_connector = Common::DBConnector.new()
          db_connector.load_conffile('conf/database.yml')
          db_connector.connect()
          name = @name.gsub(/\\/) { '' }
          name.gsub!(/'/) { "\\'" }
          page = Common::WPPage.find(:first, :conditions => "name = '#{name}'")
        end
        return to_xml(page)
      end

      private
      def to_xml(page)  
        doc = REXML::Document.new()
        doc.add(REXML::XMLDecl.new('1.0', 'UTF-8'))
        wpspider_elem = REXML::Element.new('wpspider')
        doc.add_element(wpspider_elem)
        pages_elem = REXML::Element.new('pages')
        wpspider_elem.add_element(pages_elem)
        if(page)
          page_elem = REXML::Element.new('page')
          pages_elem.add_element(page_elem)
          name_elem = REXML::Element.new('name')
          name_elem.add_text(page.name)
          page_elem.add_element(name_elem)
          size_elem = REXML::Element.new('size')
          size_elem.add_text(page.size.to_s())
          page_elem.add_element(size_elem)
          words_elem = REXML::Element.new('words')
          page_elem.add_element(words_elem)
          words = page.words.split(/<>/u)
          words.each() do |word|
            word_elem = REXML::Element.new('word')
            words_elem.add_element(word_elem)
            word_elem.add_text(word)
          end
        end
        str = String.new()
        doc.write(str, 0)
        return str
      end
    end
  end
end
